package com.ktjy.web;

import com.ktjy.entity.Auctionuser;
import com.ktjy.mapper.AuctionuserMapper;
import com.ktjy.service.AuctionuserService;
import com.ktjy.service.impl.AuctionuserServiceImpl;
import com.ktjy.util.MyBatisUtil;
import my.framework.anno.RequestMapping;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.UnrecoverableEntryException;

@Controller // 表示这个类是一个控制器
public class AuctionUserServlet {

    @RequestMapping(value = "/register")
    public void register(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            AuctionuserMapper auctionuserMapper = sqlSession.getMapper(AuctionuserMapper.class);

            //获取参数
            String userName = request.getParameter("userName");
            String userPassword = request.getParameter("userPassword");
            String userCardNo = request.getParameter("userCardNo");
            String userTel = request.getParameter("userTel");
            String userAddress = request.getParameter("userAddress");
            String userPostNumber = request.getParameter("userPostNumber");

            //验证邮政编码 长度
            if (userPostNumber == null || !userPostNumber.matches("\\d{6}")) {
                response.getWriter().write("邮政编码必须为6位数字");
                return;
            }

            Auctionuser auctionuser = new Auctionuser(userName, userPassword, userCardNo, userTel, userAddress, userPostNumber);
            auctionuserMapper.register(auctionuser);
            sqlSession.commit();
            //跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
}
